package com.wunong.smart.collection.domain.state.operation;

import com.wunong.smart.collection.application.request.BaseCollectionRequest;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 收藏域操作工厂类
 *
 * @author create by zealot.zt
 */
@SuppressWarnings("rawtypes")
@Component
public class CollectionOperationFactory implements ApplicationContextAware, SmartInitializingSingleton {

    private static Map<Class<? extends BaseCollectionRequest>, CollectionOperation> operations = new HashMap<>();

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterSingletonsInstantiated() {
        Map<String, CollectionOperation> map = applicationContext.getBeansOfType(CollectionOperation.class);
        if (MapUtils.isNotEmpty(map)) {
            map.forEach((k, v) -> operations.put(v.getRequestClass(), v));
        }
    }

    /**
     * 根据请求对象获取操作类
     *
     * @param request
     * @return
     */
    public static <REQ extends BaseCollectionRequest> CollectionOperation getOperation(REQ request) {
        return operations.get(request.getClass());
    }

}
